package com.person.mall.service.Impl;

import com.person.mall.dao.UserMapper;
import com.person.mall.pojo.User;
import com.person.mall.service.IUserService;
import com.person.mall.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

import static com.person.mall.enums.ResponseEnum.*;
import static com.person.mall.enums.RoleEnum.CUSTOMER;

/**
 * @author 最酷的桃儿wjc
 * * @date 2022/5/14
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public ResponseVo<User> registerUser(User user) {

        //用户名不能重复
        int countByUsername = userMapper.countByUsername(user.getUsername());
        if (countByUsername>0){
            return ResponseVo.error(USERNAME_EXIST);
        }
        //email不能重复
        int countByEmail = userMapper.countByEmail(user.getEmail());
        if (countByEmail>0){
            return ResponseVo.error(EXMAIL_EXIST);
        }
        //密码MD5加密（Spring自带）
        user.setPassword(
                DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8))
        );
        //设置用户初始角色都是 普通用户 -1
        user.setRole(CUSTOMER.getCode());
        //将数据插入数据库
        int resultCount = userMapper.insertSelective(user);
        if (resultCount == 0){
            return ResponseVo.error(ERROR);
        }
        return ResponseVo.success(SUCCESS);
    }


    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public ResponseVo<User> loginUser(String username, String password) {
        User user = userMapper.selectByUsername(username);
        if (user == null){
            //用户不存在（返回用户名或密码错误）
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }
        if (!user.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)))){
            //密码错误
            return ResponseVo.error(USERNAME_OR_PASSWORD_ERROR);
        }
        user.setPassword("");
        return ResponseVo.successGetData(user);
    }
}
